package cliente_admin;
import java.io.IOException;
import java.io.InputStream;
import java.security.Key;
import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;

import common.Lector_socket;
import common.Mensaje;
import control.Control;

public class ClienteAdmin {
	
	private final static int PUERTO_SERVIDOR = 5050;
	private final static String IP_SERVIDOR = "localhost";
	
	private final static String KS_PATH= "keystore/cliente_admin.jks";
	
	private SSLContext ssl_context;
	private SSLSocket socket_cliente;
	

	
	private Lector_socket lector;
	
	private Thread thread_invocante_actual;
	//private AdminMain adminGui;
	private Control adminGui;
	/**
	 * @param args
	 */

	   //public ClienteAdmin(AdminMain admin){
	public ClienteAdmin(Control admin){
		   adminGui = admin;
	   }
	   
	   
	   public boolean verificarPass(char[] pass){
		// load del archivo del keystore
		   	KeyStore key_store;
			try {
				key_store = KeyStore.getInstance("JKS");
				
				InputStream keystoreStream = getClass().getClassLoader().getResourceAsStream(KS_PATH);
			        
			   key_store.load(keystoreStream, pass);
			   
			   if(key_store.containsAlias("admin")){
				   Key key=key_store.getKey("admin", pass);
				   return key!=null;
					   
			   }
			} catch (Exception e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
				System.err.println("Password incorrecto");
				return false;
			}
	       
		   
		   return false;
	   }

	   public String iniciar_conexion(char[] pass_ks, char[] pass_keys){
		   
		   try {
			   // load del archivo del keystore
			   	KeyStore key_store = KeyStore.getInstance("JKS");
		        InputStream keystoreStream = getClass().getClassLoader().getResourceAsStream(KS_PATH);
		        
		        // inicio del keymanager a partir del keystore
		         key_store.load(keystoreStream, pass_ks);
		         KeyManagerFactory key_manager = KeyManagerFactory.getInstance("SunX509");
		         key_manager.init(key_store, pass_keys);
		         
		         // inicio del trustmanager a partir del keystore
		         TrustManagerFactory trust_store = TrustManagerFactory.getInstance("SunX509");
		         trust_store.init(key_store);
		         
		         // establezco el keystorey truststore utilizado por el socket ssl
		         ssl_context = SSLContext.getInstance("SSL");
		         ssl_context.init(key_manager.getKeyManagers(), trust_store.getTrustManagers(), null);
		         
		         // genero el socket ssl
				 SSLSocketFactory ssl_factory = ssl_context.getSocketFactory();
				 socket_cliente =(SSLSocket) ssl_factory.createSocket(IP_SERVIDOR, PUERTO_SERVIDOR);
		         
				 // inicio de handshake
				 socket_cliente.startHandshake();
		         
				 // creo el lector que permite enviar/recibir msjs del protocolo nuestro a trav�s del socket
		         lector = new Lector_socket(socket_cliente);
		         return printSocketInfo(socket_cliente);

		   	}catch (Exception e) {
		   		System.err.println(e.toString());
		   		return "No se pudo efectuar la conexi�n: "+e.toString();
		   	}
	   }
	   
	   @SuppressWarnings("deprecation")
	public Mensaje recibir_msj(){
		   Mensaje msj =lector.leer_msj();
		   
		   if(msj==null){
			   //adminGui.mostrarCierre(); // ????????????????????????????????? SEPT2014
			   cerrar_conexion();
			   thread_invocante_actual.stop();// detengo el thread que lo invoc�
			   System.out.println("se detuvo thread");
			   
			}
		   
		   return msj; 
	   }
	   
	   public void enviar_msj(Mensaje msj){
		   lector.enviar_msj(msj);
	   }
	   
	   public void cerrar_conexion(){
		try {
			lector.cerrar();
			socket_cliente.close();
		} catch (IOException e) {
			System.err.println(e.getMessage());
		}
	   }
	   
	   private String printSocketInfo(SSLSocket s) {
		   	StringBuffer sb = new StringBuffer();
		   	sb.append("Socket class: "+s.getClass()+"\n");
		   	sb.append("\tRemote address = "+s.getInetAddress().toString()+"\n");
		   	sb.append("\tRemote port = "+s.getPort()+"\n");
		   	sb.append("\tLocal socket address = "+s.getLocalSocketAddress().toString()+"\n");
		   	sb.append("\tLocal address = "+s.getLocalAddress().toString()+"\n");
		   	sb.append("\tLocal port = "+s.getLocalPort()+"\n");
		   	sb.append("\tNeed client authentication = "+s.getNeedClientAuth()+"\n");
		      
		   	SSLSession ss = s.getSession();
		   	try {
		   		sb.append("Session class: "+ss.getClass()+"\n");
		        sb.append("\tCipher suite = "+ss.getCipherSuite()+"\n");
		        sb.append("\tProtocol = "+ss.getProtocol()+"\n");
		        sb.append("\tPeerPrincipal = "+ss.getPeerPrincipal().getName()+"\n");
		        sb.append("\tLocalPrincipal = "+ss.getLocalPrincipal().getName()+"\n");
		    }catch (Exception e) {
		   		System.err.println(e.toString());
		   	}
		   	return sb.toString();
	   }

	public Thread getThread_invocante_actual() {
		return thread_invocante_actual;
	}

	public void setThread_invocante_actual(Thread thread_invocante_actual) {
		this.thread_invocante_actual = thread_invocante_actual;
	}
}
	
	


